﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Tisonet.Dobrak.Domain.Models;

namespace Tisonet.Dobrak.Client.WP8.Services.Projections
{
    public class WebProjectionsProvider : IProjectionsProvider
    {
        private readonly Uri _serverUri;

        public WebProjectionsProvider(Uri serverUri)
        {
            _serverUri = serverUri;
        }

        public void GetProjectionsAsync(Action<IEnumerable<Projection>> onReady)
        {
            var webClient = new WebClient();
            webClient.OpenReadCompleted += (sender, args) => DataDownloaded(args, onReady);
            webClient.OpenReadAsync(_serverUri);
        }

        private void DataDownloaded(OpenReadCompletedEventArgs e, Action<IEnumerable<Projection>> onDownloaded)
        {
            if (e.Cancelled || e.Error != null) return;

            using (var streamReader = new StreamReader(e.Result))
            {
                using (var jsonReader = new JsonTextReader(streamReader))
                {
                    var serializer = new JsonSerializer();
                    var projections = serializer.Deserialize<IEnumerable<Projection>>(jsonReader);

                    if (onDownloaded != null)
                    {
                        onDownloaded(projections);
                    }
                }
            }
        }
    }
}
